import pandas as pd

import util.mydecorator
import util.lib as ulib


from daily import get_daily_df


ret = None
writer = None

def built_empty_df():
    return pd.DataFrame({}, columns=["date", "stock","count","de_sum",
                                     "level_point","pct","next_pct",
                                     "close",
                                     "gt10d","gt20d","gt30d","gt60d",
                                     "category"])

def cal(item):
    global ret,writer

    stock_name = item['name']
    category = item['category']

    df = get_daily_df(stock_name).sort_index(ascending=True)
    df['next_pct'] = df['pct'].shift(-1) 

    count = 0
    de_sum = 0
    step = 0.5

    print(stock_name)
    for i,row in df['2022-01-01':].iterrows():
        pct = row['pct']
        if (pct < 0) or (de_sum !=0 and pct < step):
            de_sum += pct
            count += 1
            if de_sum < -5 :
                #print(row.name,stock_name,de_sum)
                item = {
                    "date":row.name,
                    "stock":stock_name,
                    "count": count,
                    "de_sum":de_sum,
                    "pct":pct,
                    "next_pct": row["next_pct"],
                    "level_point":row["level_point"],
                    "close":row["close"],
                    "gt10d":row["gt10d"],
                    "gt20d":row["gt20d"],
                    "gt30d":row["gt30d"],
                    "gt60d":row["gt60d"],
                    "category":category,
                }
                ret.loc[len(ret)] = item

            continue

        if de_sum != 0 and pct >= step:
            # 重置
            de_sum = 0
            count = 0
        
        if de_sum == 0 and  pct >= 0 :
            continue

@util.mydecorator.calTime
def job():

    global ret,writer

    ret = built_empty_df()
    writer = pd.ExcelWriter(ulib.data_path + "de_sum.xlsx")

    shares = ulib.lib_get_all_stock()
    shares = shares[shares['rank'] > 0]

    for _, item in shares.iterrows():
        cal(item)

    ret.to_excel(writer, index=False)
    writer.close()


if __name__ == '__main__':
    job()